var moment = require('./moment.min');
// 舍去小数点后N位
var cutFixed = function (value, decimal) {
	var times = Math.pow(10, decimal);
	return Math.floor(value * times) / times;
}

// 自动按价格取小数点位数
var cutDecimal = function (number) {
	var str = String(number);
	var length = str.split('.')[1].length
	return length;
}

// 日期格式化
let todayDateTime = (createdAt) => {
	createdAt = moment(createdAt);
	var zero = moment().format('YYYY-MM-DD');
	var after = moment(createdAt).isAfter(zero);
	if (after) {
		createdAt = moment(createdAt).format('HH:mm:ss');
	} else {
		createdAt = moment(createdAt).format('YYYY-MM-DD HH:mm:ss');
	}
	return createdAt
}

// 格式化订单
var formatOrders = function (orders) {
	var stateMap = {
		'submitted': '未成',
		'partial_filled': '部成',
		'partial_canceled': '部撤',
		'filled': '已成',
		'canceled': '已撤',
		'pending_cancel': '待撤',
	};
	return orders.map(item => {
		var created_at = moment(item.created_at);
		var zero = moment().format('YYYY-MM-DD');
		var after = moment(created_at).isAfter(zero);
		if (after) {
			item.created_at = moment(item.created_at).format('HH:mm:ss');
		} else {
			item.created_at = moment(item.created_at).format('YYYY-MM-DD HH:mm:ss');
		}
		item.stateLabel = stateMap[item.state];
		item.price = cutFixed(item.price, 6);
		item.amount = cutFixed(item.amount, 6);
		item.filled_amount = cutFixed(item.filled_amount, 6);
		return item;
	});
}

// 获取当前币种的余额
var findBalanceByCurrency = function (balanceData, currency) {
	var value = 0;
	balanceData.some(item => {
		if (item.currency === currency) {
			value = Number(item.available).toFixed(2);
			return true;
		}
	});
	return value;
}

// 设定默认币对为ftusdt
var findDefaultCurrency = function (symbols) {
	return new Promise((resolve, reject) => {
		symbols.forEach((item, index) => {
			if (item.name == 'btcusdt') {
				resolve(index);
			}
		});
		resolve(0);
	});
}

// 格式化交易深度
var formatDepth = function (depthData, length) {
	var result = {};
	for (const side in depthData) {
		if (side == 'asks' || side == 'bids') {
			var someSideArray = depthData[side];
			result[side] = someSideArray.map((item, n) => {
				return [someSideArray[2 * n], someSideArray[2 * n + 1]];
			}).filter((item, index) => {
				// console.log(length)
				if (length) {
					return index < length;
				}
				return true;
			});
		}
	}
	return result;
}

// 格式化余额
var formatBalance = function (balanceData) {
	var currencyArray = [];
	// 找到所有币种
	balanceData.forEach(item => {
		currencyArray.push(item.currency);
	});
	// 按字母表排序，得到key
	currencyArray.sort();
	var result = [];
	// 按新的顺序写回
	currencyArray.forEach(currency => {
		balanceData.forEach(balance => {
			if (balance.currency == currency) {
				result.push(balance);
			}
		});
	});
	return result.map(item => {
		item.balance = cutFixed(item.balance, 3);
		item.available = cutFixed(item.available, 3);
		item.frozen = cutFixed(item.frozen, 3);
		return item;
	}).filter(item => {
		if (item.category == 'gpm') {
			return false;
		}
		return true;
	});
}

var generateSymbols = function () {
	var array = [
		'777',
		'GUS',
		'CCCX',
		'SOC',
		'BANCA',
		'PRA',
		'BLZ',
		'DCC',
		'SSS',
		'MDT',
		'TST',
		'PMD',
		'RTE',
		'XPS',
		'TCT',
		'DWS',
		'OCN',
		'NGOT',
		'DATX',
		'AT',
		'FT',
	];
	array = [];
	var symbols = array.map(item => {
		item = {
			"name": item.toLowerCase() + 'eth',
			"base_currency": item.toLowerCase(),
			"quote_currency": "eth",
			"price_decimal": 2,
			"amount_decimal": 4
		};
		return item;
	});
	return symbols;
}

// 格式化k线数据
var formatKline = function (res) {
	var data = [];
	res.forEach(item => {
		// 对取值精度到3位小数
		for (const key in item) {
			item[key] = cutFixed(item[key], 3);
		}
		data.push([item.open, item.close, item.low, item.high]);
	});
	return data.reverse();
}

// bmob sdk适配
let formatResults = (res) => {
  if (res.length) {
    let newResults = res.map(item => {
      let result = item.attributes
      // console.log(item)
      result.objectId = item.id
      result.createdAt = item.createdAt
      // console.log(result)
      return result
    })
    return newResults
  } else {
    return []
  }
}

module.exports = {
	cutFixed,
	cutDecimal,
	formatOrders,
	formatDepth,
	formatBalance,
	formatKline,
	findBalanceByCurrency,
	findDefaultCurrency,
	generateSymbols,
	pageSize: 30,
	todayDateTime,
	formatResults,
}